package com.linkai.controller.admin.business;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linkai.controller.admin.BaseController;
import com.linkai.dto.admin.business.inputOrderReback.RebackNumberAndId;
import com.linkai.dto.admin.business.saleReback.*;
import com.linkai.entity.*;
import com.linkai.enums.R;
import com.linkai.enums.ResultDTO;
import com.linkai.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yamon
 * @since 2021-03-14
 */
@Controller
@RequestMapping("/admin/business/saleReback")
public class SaleRebackOrderController extends BaseController {
    @Autowired
    private SaleRebackOrderProductService saleRebackOrderProductService;

    @Autowired
    private SaleRebackOrderService saleRebackOrderService;

    @Autowired
    private SaleorderService saleorderService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StorageService storageService;


    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private SaleorderProductService saleorderProductService;

    @Autowired
    private MoneyaccountService moneyaccountService;

    @GetMapping("/index")
    public ModelAndView index() {
        final ModelAndView modelAndView = new ModelAndView();
        List<SaleOrderRebackIndexDto> list = saleRebackOrderService.listAll();
        modelAndView.addObject("items", list);
        modelAndView.setViewName("/admin/business/saleReback/index");
        return modelAndView;
    }


    @GetMapping("/input/{id}")
    @ResponseBody
    public R input(@PathVariable Integer id) {
        boolean flag = saleRebackOrderService.updateStorageBySaleId(id);

        return R.ok();
    }

    @GetMapping("/add")
    public ModelAndView add() {
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/business/saleReback/addTemp");
        return modelAndView;
    }

    @GetMapping("/view/{id}")
    public ModelAndView view(@PathVariable Integer id) {
        final ModelAndView modelAndView = new ModelAndView();
        UnConnectedSaveDto unConnectedSaveDto = new UnConnectedSaveDto();
        final SaleRebackOrder byId = saleRebackOrderService.getById(id);
        //证明是非关联
        unConnectedSaveDto.setOrderId(byId.getSaleOrderNumber());
        unConnectedSaveDto.setSaleId(byId.getId());
        unConnectedSaveDto.setInputDate(byId.getInpDate());
        unConnectedSaveDto.setEmployeeName(employeeService.getById(byId.getEmpId()).getName());
        unConnectedSaveDto.setPrice(byId.getPrice());
        unConnectedSaveDto.setAccountName(moneyaccountService.getById(byId.getAccId()).getAccName());
        unConnectedSaveDto.setBack(byId.getBack());
        final QueryWrapper<SaleRebackOrderProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sale_reback_order_id",byId.getId());
        final List<SaleRebackOrderProduct> list = saleRebackOrderProductService.list(queryWrapper);
        final List<ProductShowDto> productShowDtos = list.stream().map(saleRebackOrderProduct -> {
            final Storage storage = storageService.getById(saleRebackOrderProduct.getStorageId());
            ProductShowDto productShowDto = new ProductShowDto();
            productShowDto.setId(saleRebackOrderProduct.getStorageId());
            productShowDto.setStorageId(saleRebackOrderProduct.getStorageId());
            productShowDto.setProPrice(saleRebackOrderProduct.getProPrice());
            productShowDto.setProNum(saleRebackOrderProduct.getProNum());
            productShowDto.setProTitle(storage.getProTitle());
            productShowDto.setProUnit(storage.getProUnit());
            productShowDto.setEachSum(saleRebackOrderProduct.getEachSum());
            return productShowDto;
        }).collect(Collectors.toList());
        unConnectedSaveDto.setProducts(productShowDtos);
        modelAndView.addObject("item",unConnectedSaveDto);
        modelAndView.setViewName("/admin/business/saleReback/show/view");
        return modelAndView;

    }

    /**
     * 不关联销售单，直接进行退货
     *
     * @return ModelAndView
     */
    @GetMapping("/addUnConnect")
    public ModelAndView addUnConnect() {
        final ModelAndView modelAndView = new ModelAndView();
        final QueryWrapper<SaleRebackOrderProduct> queryWrapper = new QueryWrapper<>();
        saleRebackOrderProductService.list(queryWrapper);
        modelAndView.setViewName("/admin/business/saleReback/addUnConnect");
        return modelAndView;
    }

    /**
     * 得到所有已经退货的商品
     *
     * @return
     */
    @GetMapping("/getAllSaledProduct")
    @ResponseBody
    public R getAllSaledProduct() {
        //查出所有销售单内的商品，然后选中，退货
        List<ProductShowDto> list = saleRebackOrderProductService.getAllSaledProducts();
        return R.ok().data("list", list);
    }

    /**
     * 非关联商品销售退货，保存退货单
     *
     * @param rebackOrder
     * @return
     */
    @PostMapping("/unConnectSave")
    @ResponseBody
    public ResultDTO<Boolean> saveUnConnectProduct(@RequestBody UnConnectedSaveDto rebackOrder) {
        //保存整张单子
        final SaleRebackOrder entity = new SaleRebackOrder();
        entity.setSaleOrderNumber(rebackOrder.getOrderId());
        entity.setEmpId(rebackOrder.getEmployeeId());
        entity.setAccId(rebackOrder.getAccountMoeny());
        entity.setPrice(rebackOrder.getPrice());
        entity.setInpDate(rebackOrder.getInputDate());
        entity.setBack(rebackOrder.getBack());
        //证明非关联销售单
        entity.setSaleId(-1);
        if (saleRebackOrderService.save(entity)) {
            //保存到多表
            for (ProductShowDto product : rebackOrder.getProducts()) {
                final SaleRebackOrderProduct saleRebackOrderProduct = new SaleRebackOrderProduct();
                saleRebackOrderProduct.setSaleRebackOrderId(entity.getId());
                saleRebackOrderProduct.setProNum(product.getProNum());
                saleRebackOrderProduct.setProPrice(product.getProPrice());
                saleRebackOrderProduct.setStorageId(product.getId());
                saleRebackOrderProduct.setEachSum(product.getEachSum());
                saleRebackOrderProduct.setProState(0);
                saleRebackOrderProductService.save(saleRebackOrderProduct);
            }
            return super.successSaveInfo(true);
        }
        return super.successSaveInfo(false);
    }

    /**
     * 返回所有的销售单 TODO:待优化
     *
     * @return list
     */
    @GetMapping("listAllSaleOrders")
    @ResponseBody
    public R listAllSaleRebackOrders() {
        List<TableIndexDto> saleOd = new ArrayList<>();
        //设置
        final List<Saleorder> list = saleorderService.list();
        for (Saleorder saleorder : list) {
            final TableIndexDto tableIndexDto = new TableIndexDto();
            tableIndexDto.setId(saleorder.getId());
            tableIndexDto.setInputOrderNumber(saleorder.getOrderNumber());
            tableIndexDto.setInpDate(saleorder.getInpDate());
            tableIndexDto.setPrice(saleorder.getPrice());
            tableIndexDto.setCusName(customerService.getById(saleorder.getCusId()).getName());
            final QueryWrapper<SaleorderProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("storage_id");
            queryWrapper.eq("order_id", saleorder.getId());
            final List<SaleorderProduct> saleorderProducts = saleorderProductService.list(queryWrapper);
            List<Integer> storageId = saleorderProducts.stream().map(SaleorderProduct::getStorageId).collect(Collectors.toList());
            final List<Storage> storages = storageService.listByIds(storageId);
            List<String> proNames = storages.stream().map(Storage::getProTitle).collect(Collectors.toList());
            tableIndexDto.setProName(proNames);
            saleOd.add(tableIndexDto);
        }
        return R.ok().data("data", saleOd);
    }


    /**
     * 关联销售单
     *
     * @param id 销售单id
     * @return 信息
     */
    @GetMapping("/addConnect/{id}")
    public ModelAndView addConnect(@PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        UnConnectedSaveDto unConnectedSaveDto = new UnConnectedSaveDto();
        final Saleorder byId = saleorderService.getById(id);
        unConnectedSaveDto.setSaleId(byId.getId());
        unConnectedSaveDto.setOrderId(byId.getOrderNumber());
        unConnectedSaveDto.setInputDate(byId.getInpDate());
        unConnectedSaveDto.setEmployeeName(employeeService.getById(byId.getEmpId()).getName());
        //设置商品
        final QueryWrapper<SaleorderProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", id);
        final List<SaleorderProduct> saleorderProducts = saleorderProductService.list(queryWrapper);
        List<ProductShowDto> list = saleorderProducts.stream().map(saleorderProduct -> {
            final ProductShowDto productShowDto = new ProductShowDto();
            productShowDto.setId(saleorderProduct.getStorageId());
            final Storage storage = storageService.getById(saleorderProduct.getStorageId());
            productShowDto.setProTitle(storage.getProTitle());
            productShowDto.setProNum(storage.getProNum());
            productShowDto.setProUnit(storage.getProUnit());
            productShowDto.setProPrice(storage.getProPrice());
            productShowDto.setEachSum(saleorderProduct.getEachSum());
            return productShowDto;
        }).collect(Collectors.toList());
        unConnectedSaveDto.setProducts(list);
        unConnectedSaveDto.setPrice(byId.getPrice());
        unConnectedSaveDto.setAccountName(moneyaccountService.getById(byId.getAccId()).getAccName());
        unConnectedSaveDto.setBack(byId.getBack());
        //查找出销售单的所有商品
        modelAndView.addObject("item", unConnectedSaveDto);
        modelAndView.setViewName("/admin/business/saleReback/addConnect");
        return modelAndView;
    }

    /**
     * 关联退货单退货
     *
     * @return
     */
    @PostMapping("/connectSave/{saleId}")
    @ResponseBody
    public R connectSave(@RequestBody ConnectedSaveDto connectedSaveDto, @PathVariable Integer saleId) {
        final SaleRebackOrder entity = new SaleRebackOrder();
        entity.setSaleOrderNumber(connectedSaveDto.getOrderId());
        entity.setSaleId(saleId);
        entity.setEmpId(connectedSaveDto.getEmployeeId());
        entity.setPrice(connectedSaveDto.getPrice());
        entity.setAccId(connectedSaveDto.getAccountMoeny());
        entity.setBack(connectedSaveDto.getBack());
        entity.setInpDate(connectedSaveDto.getInputDate());
        boolean flag = saleRebackOrderService.save(entity);
        if (flag) {
            //保存成功
            final List<RebackNumberAndId> products = connectedSaveDto.getProducts();
            for (RebackNumberAndId product : products) {
                final SaleRebackOrderProduct saleRebackOrderProduct = new SaleRebackOrderProduct();
                saleRebackOrderProduct.setSaleRebackOrderId(saleId);
                final Storage byId = storageService.getById(product.getId());
                saleRebackOrderProduct.setProPrice(byId.getProPrice());
                saleRebackOrderProduct.setStorageId(byId.getId());
                saleRebackOrderProduct.setProNum(product.getNum());
                BigDecimal bg = new BigDecimal(product.getNum());
                saleRebackOrderProduct.setEachSum(byId.getProPrice().multiply(bg));
                saleRebackOrderProductService.save(saleRebackOrderProduct);
            }
            return R.ok();
        }
        return R.error();
    }


}

